<script setup lang="ts">
import { onMounted, ref, unref, reactive } from 'vue'
import { useBaseApi } from '@/api/base'
import { clone } from 'xe-utils'
import { dayjs, ElMessage } from 'element-plus'
import mittBus from '@/utils/mitt'
import type { VxeGridProps } from 'vxe-table'
import type { BusinessUIAction } from '@/types/custom'

const { CustomRequest } = useBaseApi()

interface Props {
  _action?: BusinessUIAction
  _params: TypedAny
  defaultParams?: TypedAny
}

interface RowType {
  amt_borrow: number
  amt_can_deduction: number
  amt_this_deduction: number
  borrow_app_date: string
  borrow_dep_name: string
  borrow_id: string
  borrow_org_name: string
  borrow_own_user_name: string
  borrow_use_kind: string
  borrow_used: string
  deduction_id: string
  expense_id: string
}

const props = defineProps<Props>()
const emit = defineEmits(['close', 'fetch'])

const xGrid = ref()
const loading = ref(false)
const params = ref<TypedAny>({})
const gridOptions = reactive<VxeGridProps<RowType>>({
  keepSource: true,
  showOverflow: true,
  height: 'auto',
  loading: false,
  columnConfig: {
    resizable: true
  },
  columns: [
    { type: 'seq', width: 50 },
    { field: 'borrow_app_date', title: '借款日期', width: 130 },
    { field: 'borrow_dep_name', title: '借款部门', width: 130 },
    { field: 'borrow_org_name', title: '借款公司', width: 130 },
    { field: 'borrow_own_user_name', title: '借款借款人', width: 100 },
    { field: 'borrow_use_kind', title: '用途类型', width: 100 },
    { field: 'borrow_used', title: '用途', width: 200, align: 'left' },
    { field: 'amt_borrow', title: '借款金额', width: 100 },
    { field: 'amt_can_deduction', title: '可冲抵金额', width: 100 },
    {
      field: 'amt_this_deduction',
      title: '本次冲抵金额',
      width: 200,
      slots: {
        default: 'deduction'
      }
    }
  ]
})

const gridData = ref<RowType[]>([])

/**
 * 格式化参数
 */
const onFormatParams = () => {
  if (props._action && props.defaultParams) {
    params.value = {}
    const default_value_parse = props._action.default_value_parse
    if (Object.keys(default_value_parse).length) {
      for (const k in default_value_parse) {
        params.value[k] = props.defaultParams[k] || default_value_parse[k]
      }
    } else {
      params.value = clone(props.defaultParams, true)
    }
  }
}

/**
 * 获取路径
 */
const getUrl = (): string => {
  const param = unref(params)
  if (param.gathering_id) {
    // 收款管理 - 获取可冲抵的借款明细
    return '/api-mis/AccountGathering/gathering_deduction_borrows'
  } else if (param.pro_expense_id) {
    // 采购报销 - 获取可冲抵的借款明细
    return '/api-mis/ProExpense/expense_deduction_borrows'
  } else {
    // 报销申请 - 获取可冲抵的借款明细
    return '/api-mis/AccountExpense/expense_deduction_borrows'
  }
}

/**
 * 获取报销申请可冲抵的借款明细
 */
const onFetch = () => {
  loading.value = true
  const param = unref(params)
  CustomRequest({
    url: getUrl(),
    method: 'get',
    params: param
  })
    .then(({ data }) => {
      const option: TypedAny = { 1: '普通', 2: '机票充值', 3: '采购' }
      data.forEach((v: RowType) => {
        v.borrow_use_kind = option[v.borrow_use_kind] || v.borrow_use_kind
        v.borrow_app_date = dayjs(v.borrow_app_date).format('YYYY-MM-DD HH:mm')
      })
      gridData.value = data
    })
    .finally(() => (loading.value = false))
}

/**
 * 保存
 */
const onSave = async () => {
  if (xGrid.value) {
    const param = unref(params)
    const { fullData } = xGrid.value.getTableData()
    return CustomRequest({
      url: getUrl(),
      method: 'post',
      params: param,
      data: { rows: fullData }
    }).then(({ data }) => {
      if (data && data.forms && data.forms.length) {
        // 把数据发送给父级
        mittBus.emit('onUpdateParent', data)
      }
      ElMessage.success('保存成功')
      emit('fetch')
      return data
    })
  } else {
    return Promise.resolve()
  }
}

onMounted(() => {
  // console.log(props._action)
  // console.log(props._params)
  // console.log(props.defaultParams)
  onFormatParams()
  onFetch()
})

defineExpose({ onSave })
</script>

<template>
  <vxe-grid ref="xGrid" v-bind="gridOptions" :data="gridData" :loading="loading" append-to-body>
    <template #deduction="{ row, column }">
      <el-input-number v-model="row[column.field]" :min="0" />
    </template>
  </vxe-grid>
</template>
